<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 左侧 -->
          <el-tab-pane label="角色管理">
            <!-- 新增按钮 -->
            <el-button icon="el-icon-plus" size="small" type="primary" @click="showDialog = true">新增角色</el-button>
            <!-- 角色表格 -->
            <el-table id="margin" v-loading="loading" :data="rowsList" border>
              <el-table-column label="序号" width="100" type="index" :index="indexMethod" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template v-slot="{row}">
                  <el-button size="small" type="success" @click="clickShowAssignDialog(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="editRole(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="delRole(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!--
            角色数据分页
            current-page:当前页码值(现在在第几页)
            page-sizes:每页可显示的页码个数
            page-size:当页显示的每页数据条数
            layout:分页组件布局
            total:数据总条数

            size-change:显示的数据条数发送改变时触发
            current-change:页码值改变时触发
            -->
            <el-pagination
              :current-page="page"
              :page-sizes="[1, 3, 5,10]"
              :page-size="pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
            />

          </el-tab-pane>
          <el-tab-pane label="公司信息">
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyForm.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyForm.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyForm.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyForm.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>

          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 新增与编辑的弹出框 -->
      <el-dialog :title="showTitle" :visible="showDialog" @close="handleClose">

        <el-form ref="roleForm" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="form.description" placeholder="请输入角色描述" />
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="AddRole">确认</el-button>
        </template>

      </el-dialog>

      <el-dialog title="分配权限" :visible="showAssignDialog" @close="closeAssignDialog" @open="openAssignDialog">
        <!-- 树型数据渲染 -->
        <el-tree
          ref="tree"
          :data="permissionData"
          :props="{label:'name'}"
          default-expand-all
          show-checkbox
          check-strictly
          node-key="id"
        />

        <template #footer>
          <div style="text-align: right;">
            <el-button @click="closeAssignDialog">取消</el-button>
            <el-button type="primary" @click="clickAssign">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { reqGetRoleList, reqDeleteRole, reqAddRole, reqGetRoleDetail, reqUpdateRole, reqAssignPerm } from '@/api/setting'
import { reqGetCompanyById } from '@/api/company'
import { reqGetPermissionList } from '@/api/permisson'
import { tranListToTree } from '@/utils'
// import { mapState } from 'vuex'
export default {
  name: 'Setting',
  data() {
    return {
      activeName: 'role',

      page: 1, // 当前页

      pagesize: 10, // 几条每页

      rowsList: [], // 角色信息储存

      total: 0, // 共多少条

      loading: false, // 加载效果

      showDialog: false, // 新增和编辑弹窗

      companyForm: {}, // 公司信息

      index: {}, // 自定义序号

      showAssignDialog: false, // 分配权限弹框

      permissionData: [], // 存储树型数据

      roleId: '',

      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  computed: {
    showTitle() {
      return this.form.id ? '编辑角色' : '新增角色'
    }
    // ...mapState('user', ['userInfo'])
  },
  created() {
    this.getRoleList()
    this.getCompanyInfo()
  },
  methods: {
    // 获取数据
    async getRoleList() {
      this.loading = true
      const { data: { rows, total }} = await reqGetRoleList(this.page, this.pagesize)
      this.rowsList = rows
      this.total = total
      this.loading = false
    },
    // 每页多少条 显示的数据条数发送改变时触发
    handleSizeChange(newSize) {
      this.pagesize = newSize
      this.getRoleList()
    },
    // 当前页 页码值改变时触发
    handleCurrentChange(newPage) {
      this.page = newPage
      this.getRoleList()
    },
    // 自定义index
    indexMethod(index) {
      return (this.page - 1) * this.pagesize + index + 1
    },
    // 删除
    async delRole(id) {
      const ress = await this.$confirm('确定删除吗?', '提示').catch(error => error)
      if (ress !== 'confirm') return
      const res = await reqDeleteRole(id) // 发送axios
      this.$message.success(res.message) // 删除提示
      this.getRoleList()
    },
    // 弹窗X按钮
    handleClose() {
      this.showDialog = false
      this.$refs.roleForm.resetFields()
      this.form = {
        name: '',
        description: ''
      }
    },
    // 新增角色
    AddRole() {
      this.$refs.roleForm.validate(async valid => {
        if (!valid) return
        if (this.form.id) {
          // 编辑
          const res = await reqUpdateRole(this.form)
          this.$message.success(res.message)
        } else {
          // 新增
          const res = await reqAddRole(this.form)
          this.$message.success(res.message)
        }
        this.getRoleList() // 调用函数 重新渲染
        this.handleClose() // 调用X按钮函数 关闭和清空form表单
      })
    },
    // 编辑角色
    async editRole(id) {
      this.showDialog = true
      const res = await reqGetRoleDetail(id)
      this.form = res.data
    },
    // 获取公司信息
    async getCompanyInfo() {
      // const res = await reqGetCompanyById(this.userInfo.companyId)
      const res = await reqGetCompanyById(this.$store.state.user.userInfo.companyId)
      this.companyForm = res.data
    },
    // 分配权限弹出框
    clickShowAssignDialog(id) {
      this.showAssignDialog = true
      this.roleId = id
    },
    // 分配权限弹出框 X按钮
    closeAssignDialog() {
      this.showAssignDialog = false
      this.$refs.tree.setCheckedKeys([]) // 取消时清空被选中状态
    },
    // 打开弹窗时的回调函数open 获取数据渲染成树型数据
    async openAssignDialog() {
      // 转换成树型数据
      const res = await reqGetPermissionList()
      this.permissionData = tranListToTree(res.data, '0')

      // 获取角色详情   回显默认的权限
      const { data } = await reqGetRoleDetail(this.roleId)
      // console.log(data.permIds)
      this.$refs.tree.setCheckedKeys(data.permIds)
    },
    // 点击确定分配权限
    async clickAssign() {
      const res = await reqAssignPerm({ id: this.roleId, permIds: this.$refs.tree.getCheckedKeys() })
      this.$message.success(res.message)
      this.closeAssignDialog()
      this.openAssignDialog()
    }

  }
}
</script>

<style scoped lang="scss">
 #margin{
    margin: 15px 0;
 }
</style>
